<?php
/**
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;




use app\common\facade\Func;
use think\Db;

class Card extends ApiCommon
{
    protected $table = 'lite_coupons';
    protected $orderTable = 'lite_order';
    protected $memberTable = 'store_member';

    public function __construct()
    {
        parent::__construct();
        $this->config = config('wechat.miniapp');
    }

    public function getCardList()
    {
        $card = db('lite_card')->where(['is_deleted' => 0])->select();
       $this->success('', $card);
    }

    //获取储值卡
    public function getAmount()
    {
        $user = db('store_member')->where(['openid' => $this->openid])->field('amount,use_amount')->find();
        $amount = $user['amount'] - $user['use_amount'];
        $res['amount'] = number_format($amount, 2, '.', '');
        //充值记录
        $record = db('lite_member_amount_record')->where(['open_id' => $this->openid])->select();
        foreach ($record as $key => $value){
            $record[$key]['source_type'] =  $value['type']== 0 ? '使用': '充值';
//            $record[$key]['create_time'] =  substr($value['create_time'], 0, 10);
        }
        $res['record'] = $record;
        $this->success('', $res);
    }

    public function doPay()
    {
        $data = $this->request->param();
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        if(empty($data['card_id']) || empty($data['number'])){
            $this->error('缺失参数！');
        }
        $cardInfo = db('lite_card')->where(['id' => $data['card_id']])->find();

        $orderId = $this->createOrder($cardInfo);
        if($orderId){
            $orderInfo = db($this->orderTable)->where(['id' => $orderId])->find();
            $orderInfo['body'] = $cardInfo['name'] . '(价格:'. $cardInfo['price'] .';数量x'.$data['number'] .')';
//            var_dump($orderInfo['body']);exit;
            $wxPay = new WxPay();
            $data = $wxPay->unifiedOrderCard($orderInfo);
            $data['orderId'] = $orderId;
            $this->success('', $data);
        }else{
            $this->error('创建订单失败！');
        }
    }

    public function createOrder($cardInfo)
    {
        $data = $this->request->param();
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        if(empty($data['card_id']) || empty($data['number'])){
            $this->error('缺失参数！');
        }
        $totalPrice = 0;
        $totalPrice = $cardInfo['price'] * $data['number'];

        $insertData = [
            'user_id' => $this->openid,
            'price' => $totalPrice,
            'product_id' => $data['card_id'],
            'status' => 2, //订单状态(0已取消1预订单待补全2新订单待支付3已支付待审核4审核通过5审核未通过)
            'pay_status' => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'count' => $data['number'],
            'order_sn' => $this->createOrderSn(),
            'order_type' => 1, //订单类型 0 活动报名 1 储值卡充值
        ];

        // 启动事务
        Db::startTrans();
        try {
            //字段+1
//            Db::table($this->activityTable)->setInc('has_count');
            $orderId = Db::table($this->orderTable)->insertGetId($insertData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('创建订单失败！'. $e, [Db::table($this->orderTable)->getLastSql()]);
        }
        if(isset($orderId)){
            return $orderId;
        }else{
            return false;
        }
    }

    private function createOrderSn(){
        return  date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }


    public function wxCallback()
    {
        $wechat = \We::WePayOrder($this->config);
        $notify = $wechat->getNotify();
        if ($notify['result_code'] == 'SUCCESS' && $notify['return_code'] == 'SUCCESS') {
            if ($this->update($notify['out_trade_no'], $notify['transaction_id'], $notify['cash_fee'] / 100, 'lite_app')) {
                return $wechat->getNotifySuccessReply();
            }
        } else return $wechat->getNotifySuccessReply();
    }


    /**
     * 订单状态更新
     * @param string $order_no 订单号
     * @param string $pay_no 交易号
     * @param string $pay_price 交易金额
     * @param string $type 支付类型
     * @return boolean
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function update($order_no, $pay_no, $pay_price, $type = 'wechat')
    {
        $where = ['order_sn' => $order_no, 'pay_status' => '0', 'status' => '2'];
        // 检查订单支付状态
        $order = db('lite_order')->where($where)->find();

        if (empty($order)) return false;
        db::startTrans();
        // 更新订单支付状态
        $result = db::table('lite_order')->where($where)->update([
            'pay_type'  => $type, 'pay_no' => $pay_no, 'status' => '4',
            'pay_price' => $pay_price, 'pay_status' => '1', 'pay_at' => date('Y-m-d H:i:s'),
        ]);
        // 调用会员升级机制
//        Order::update($order['order_no']);
        //更新记录和余额
        $result2 = db::table($this->memberTable)->where(['openid' => $order['user_id']])->setInc('amount', $pay_price);
        //记录账户余额变化
        $record = db::table('lite_member_amount_record')->insert([
            'open_id' => $order['user_id'],
            'type' => 1, //类型(1 加 0 -)
            'card_id' => $order['product_id'],
            'price' => $pay_price/$order['count'],
            'count' => $order['count'],
            'total_price' => $pay_price,
            'order_sn' => $order['order_sn'],
            'source_type' => 0, //来源0小程序充值1后台充值
            'create_time' => date('Y-m-d H:i;s'),
        ]);
        if($result && $record && $result2){
            db::commit();
            return true;
        }else{

            db::rollback();
            return false;
        }
    }


    public function checkPay()
    {
        $orderId = $this->request->param('id');
        if(empty($orderId)){
            $this->error('请传入订单ID！');
        }
        $orderInfo = db($this->orderTable)->find($orderId);
        //'pay_no' => $pay_no, 'status' => '1','pay_price' => $pay_price, 'pay_status' => '1',
        if($orderInfo['pay_status'] == 1 && $orderInfo['status'] == 4 && !empty($orderInfo['status'])){
            $res['paySuccess'] = true;
            $this->success('支付成功！', $res);
        }
        $res['paySuccess'] = false;
        $this->error('支付失败!', $res);
    }



}